package com.kms.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.neoremind.sshxcute.core.ConnBean;
import net.neoremind.sshxcute.core.IOptionName;
import net.neoremind.sshxcute.core.Result;
import net.neoremind.sshxcute.core.SSHExec;
import net.neoremind.sshxcute.exception.TaskExecFailException;
import net.neoremind.sshxcute.task.CustomTask;
import net.neoremind.sshxcute.task.impl.ExecCommand;

import com.kms.console.JSchConsole;
import com.kms.derby.Connections;
import com.kms.model.MGroup;
import com.kms.model.MSyspara;
import com.kms.model.SystemParameterBean;
import com.kms.service.SystemparameterService;

public class DatabaseBackupServlet extends HttpServlet{
	SystemparameterService sysservice ;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		sysservice = (SystemparameterService)Connections.getServiceBean(request, "sysparaService");
		HttpSession session = request.getSession();
		JSchConsole jc = new JSchConsole();
		
//		String command = "";
//		command = "cd dpdir;zip exim_kms.zip exim_kms_20110705.dmp";
//		command = "exp kms/kms@kobra file=/home/kms/001.dmp tables=accentry2 log=/home/kms/001.log";
		StringBuffer command = new StringBuffer();
		//linux unix 
//		command.append("exp kms/kms@kobra file=/home/kms/accentry2.dmp tables=accentry2 query="+"\\"+"\"where settledate \\= 20110702"+"\\"+"\" log=/home/kms/accentry2.log ;");
//		command.append("exp kms/kms@kobra file=/home/kms/balance.dmp tables=balance query="+"\\"+"\"where settledate \\= 20110702"+"\\"+"\" log=/home/kms/balance.log ;");
		//windows
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String datetime = sdf.format(new Date());
		List<SystemParameterBean> listsysbean = getListSysSetting(request);
		String host = "";
		String user = "";
		String pwd = "";
		String dir = "";
		String dirctory = "";
		String commandstr ="";
		int port = 0;
		
		
		String id = request.getParameter("id");
		MSyspara mssysapp=new MSyspara();
		MSyspara mssysdb=new MSyspara();
		MGroup mgroup = new MGroup();
		if(id !=null && !"null".equals(id)){
			try {
				mgroup = sysservice.selectmGroup(id);
				for(MSyspara sys:mgroup.getListsyspara()){
					if("APP".equals(sys.getDatatype())){
						mssysapp = sys;
					}else if("DB".equals(sys.getDatatype())){
						mssysdb = sys;
					}
				}
			} catch (NumberFormatException e) {
			}
			
			//DB user
			if(mssysdb!=null){
				host = mssysdb.getOsip();
				user = mssysdb.getOsuser();
				pwd = mssysdb.getOspwd();
				dir = mssysdb.getDbzipdir();
				try {
					port = Integer.valueOf(mssysdb.getOsport());
				} catch (NumberFormatException e) {
				}
			}
		}
		String ret="";
		String status = request.getParameter("status1");
		String commands = request.getParameter("commands");
		command.append("ll;");
		try {
			if("linuxcommand".equals(status) && commands!=null){
				command = new StringBuffer();
				command.append(commands);
			}else if("dbback".equals(status)){
				List<String[]> infocommandlist = new ArrayList<String[]>();
				infocommandlist.add(new String[]{"kms"," cat .bash_profile"});
				infocommandlist.add(new String[]{"bond"," cat .bash_profile"});
				for(String[] infotype:infocommandlist){
					ret = ret + jc.sshExecute(host, user, pwd, infotype[1], port);
					String[] l = ret.split("\n");
					StringBuffer _s=new StringBuffer();
					for(String r:l){
						if(r.contains("export") || r.contains("DISPLAY") || r.contains("JAVA_HOME") || r.contains("CLASSPATH") || r.contains("PATH") ){
							_s.append(r);
							_s.append("\n");
						}
					}
					_s.append("expdp ");
					if("kms".equals(infotype[0])){
						_s.append(mssysdb.getKmsuser()+"/"+mssysdb.getKmspwd());
						_s.append("@"+mssysdb.getKmsinstance());
						_s.append(" directory="+mssysdb.getKmsdirectory());
					}else if("bond".equals(infotype[0])){
						_s.append(mssysdb.getBonduser()+"/"+mssysdb.getBondpwd());
						_s.append("@"+mssysdb.getBondinstance());
						_s.append(" directory="+mssysdb.getBonddirectory());
					}
					_s.append(" dumpfile="+infotype[0]+datetime+".dmp");
					_s.append(" logfile="+infotype[0]+datetime+".log");
					if("bond".equals(infotype[0])){
						_s.append(" rows=n ");
					}
					_s.append(" schemas="+infotype[0]+" ;");
//					_s.append("expdp kms/kms@kobra directory=dmpdir dumpfile=kms201108029.dmp logfile=kms201108029.log schemas=kms ;");					ret = ret + jc.sshExecute(host, user, pwd, _s.toString(), port);
					
					ret =ret+ jc.sshExecute(host, user, pwd, _s.toString(), port);
					
					if("kms".equals(infotype[0])){
						dirctory = mssysdb.getKmsdirectorypath();
						commandstr ="cd "+dirctory+" ; zip expdp_"+infotype[0]+datetime+".zip "+infotype[0]+datetime+".* ;";
						ret =ret+ jc.sshExecute(host, user, pwd, commandstr, port);
						
						//scp /home/kms/kms_server_update.log root@192.168.8.10:/home/kms/monitor
						commandstr = "scp "+dirctory+"/expdp_kms"+datetime+".zip root@"+mssysapp.getTbsmonitorosip()+":"+mssysdb.getDbzipdir();
						ret =ret+ jc.sshExecute(host, user, pwd, commandstr, port);
						
					}else if("bond".equals(infotype[0])){
						dirctory = mssysdb.getBonddirectorypath();
						commandstr ="cd "+dirctory+" ; zip expdp_"+infotype[0]+datetime+".zip "+infotype[0]+datetime+".* ;";
						ret =ret+ jc.sshExecute(host, user, pwd, commandstr, port);
						
						commandstr = "scp "+dirctory+"/expdp_bond"+datetime+".zip root@"+mssysapp.getTbsmonitorosip()+":"+mssysdb.getDbzipdir();
						ret =ret+ jc.sshExecute(host, user, pwd, commandstr, port);
					}
					
					commandstr = "cd "+dirctory+";rm *"+datetime+".*";
					try{
						port = Integer.valueOf(mssysdb.getOsport());
					}catch(Exception ex){}
					ret =ret+ jc.sshExecute(mssysdb.getOsip(), mssysdb.getOsuser(), mssysdb.getOspwd(), commandstr, port);
				}
			}else if("remove".equals(status)){
				command = new StringBuffer();
				command.append("cd "+mssysdb.getDbzipdir()+"; rm "+mssysdb.getDbzipdir()+"/expdp_*.* ;");
				command.append("ll;");
				try{
					port = Integer.valueOf(mssysapp.getOsport());
				}catch(Exception ex){}
				ret =ret+ jc.sshExecute(mssysapp.getOsip(), mssysapp.getOsuser(), mssysapp.getOspwd(), command.toString(), port);
			}
		} catch (Exception e) {
			ret = e.toString();
			e.printStackTrace();
		}
		
		request.setAttribute("dir", dir);
		request.setAttribute("command", ret);
		request.setAttribute("listsysbean", listsysbean);
		request.setAttribute("id", id);
		request.setAttribute("listmgroup",  sysservice.selectAllMGroup());
		request.setAttribute("mssysapp", mssysapp);
		request.setAttribute("mssysdb", mssysdb);
		request.getRequestDispatcher("datebasebackup.jsp").forward(request,response); 
		return;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		sysservice = (SystemparameterService)Connections.getServiceBean(request, "sysparaService");
		doGet(request, response);
	}
	
	public List<SystemParameterBean> getListSysSetting(HttpServletRequest request){
		List<SystemParameterBean> listsysbean = new ArrayList<SystemParameterBean>();
		try {
			Connection conn = Connections.getConnection(request);
			String SQL = "SELECT * FROM SYSSETTING";
			PreparedStatement stmt = conn.prepareStatement(SQL);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				SystemParameterBean sysb = new SystemParameterBean();
				sysb.setId(rs.getInt("Id"));
				sysb.setName(rs.getString("Name"));
				sysb.setType(rs.getString("Type"));
				sysb.setValue(rs.getString("Value"));
				sysb.setEnabled(rs.getString("Enabled"));
				sysb.setDescription(rs.getString("Description"));
				listsysbean.add(sysb);
			}
			
			rs.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return listsysbean;
	}

	public void expdpcommand(){
		
	}
	
	public void uploadcommand(){
		SSHExec ssh = null;
		try {
			SSHExec.setOption(IOptionName.HALT_ON_FAILURE, false);
			SSHExec.setOption(IOptionName.SSH_PORT_NUMBER, 22);
			ConnBean cb = new ConnBean("192.168.8.10", "kms","kms");
			ssh = SSHExec.getInstance(cb);		
			CustomTask ct2 = new ExecCommand("ls;");
			ssh.connect();
			ssh.uploadSingleDataToServer("/home/kms/kms.rar", "/home/kms/monitor");
			Result res = ssh.exec(ct2);
			if (res.isSuccess)
			{
				System.out.println("R1 Return code: " + res.rc);
				System.out.println("R1 sysout: " + res.sysout);
			}
		} catch (TaskExecFailException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ssh.disconnect();	
		}
	}
	
}
